/*
 * 文件名：AreaController.java
 * 版权：Copyright by 联通系统集成有限公司
 * 描述： 修改人：焦凯旋
 * 修改时间：2019年6月13日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.bicycle.platform.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bicycle.common.entity.base.DataGrid;
import com.bicycle.common.entity.base.Message;
import com.bicycle.common.enums.*;
import com.bicycle.common.helper.CoordinateHelper;
import com.bicycle.common.helper.ExcelHelper;
import com.bicycle.common.helper.RedisStringHelper;
import com.bicycle.service.config.MyBatisPlusConfig;
import com.bicycle.service.dto.*;
import com.bicycle.service.entity.*;
import com.bicycle.service.service.*;
import com.bicycle.service.vo.*;
import com.bicycle.service.cache.DataCacheOprator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.OutputStream;
import java.util.*;


@Api(tags = "停放资源相关功能")
@Slf4j
@RestController
@RequestMapping("/area")
public class AreaController extends BaseController {

    @Autowired
    private IBicycleFacilitiesGovAreaService facilitiesGovAreaService;
    @Autowired
    private RedisStringHelper redisStringHelper;
    @Autowired
    private Environment environment;
    @Autowired
    private IBicycleSequenceReportDetailService reportDetailService;
    @Autowired
    private IBicycleBasicsNoRecordService bicycleBasicsNoRecordService;
    @Autowired
    private IBicycleFacilitiesEnterpriseAreaService facilitiesEnterpriseAreaService;
    @Autowired
    private IBicycleBasicsAreaVehicleService vehicleService;
    @Autowired
    private IBicycleDataBicycleSiteService bicycleSiteService;
    @Autowired
    private IBicycleBasicsBicycleService basicsBicycleService;
    @Autowired
    private IBicycleBasicsAreaVehicleService areaVehicleService;


    /**
     * 分页查询政府区域列表信息
     *
     * @param bicycleFacilitiesGovAreaGridDto
     * @return
     * @see
     */
    @ApiOperation("分页查询区域列表信息")
    @RequestMapping(value = "/selectGovAreaGrid", method = {RequestMethod.POST})
    public DataGrid<BicycleFacilitiesGovAreaGridVo> selectGovAreaGrid(@RequestBody BicycleFacilitiesGovAreaGridDto bicycleFacilitiesGovAreaGridDto, HttpServletRequest httpServletRequest) {
        DataGrid dataGrid = new DataGrid();
        QueryWrapper<BicycleFacilitiesGovArea> queryWrapper = new QueryWrapper<BicycleFacilitiesGovArea>();
        BicycleFacilitiesGovArea queryEntity = new BicycleFacilitiesGovArea();

        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        if (userLoginResp.getRegionId() != null) {
            bicycleFacilitiesGovAreaGridDto.setDistrict(userLoginResp.getRegionId());
        }
        BeanUtil.copyProperties(bicycleFacilitiesGovAreaGridDto, queryEntity);
        queryEntity.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());

        if (StringUtils.isNotBlank(bicycleFacilitiesGovAreaGridDto.getAreaName())) {
            queryEntity.setAreaName(null);
            queryWrapper.like("area_name", bicycleFacilitiesGovAreaGridDto.getAreaName().trim());
        }
        if (StringUtils.isNotBlank(bicycleFacilitiesGovAreaGridDto.getAreaNo())) {
            queryEntity.setAreaNo(null);
            queryWrapper.like("area_no", bicycleFacilitiesGovAreaGridDto.getAreaNo());
        }
        // 创建时间区间段筛选
        if (bicycleFacilitiesGovAreaGridDto.getBeginTime() != null && bicycleFacilitiesGovAreaGridDto.getEndTime() != null) {
            queryWrapper.between("create_time", bicycleFacilitiesGovAreaGridDto.getBeginTime(), bicycleFacilitiesGovAreaGridDto.getEndTime());
        }
        queryWrapper.setEntity(queryEntity);
        queryWrapper.orderByDesc("create_time");

        IPage<BicycleFacilitiesGovArea> page = facilitiesGovAreaService.page(new Page<BicycleFacilitiesGovArea>(bicycleFacilitiesGovAreaGridDto.getPage(), bicycleFacilitiesGovAreaGridDto.getRows()), queryWrapper);

        List<BicycleFacilitiesGovAreaGridVo> bicycleFacilitiesGovAreaResps = new ArrayList<>();
        page.getRecords().forEach(bicycleFacilitiesGovArea -> {
            BicycleFacilitiesGovAreaGridVo bicycleFacilitiesGovAreaResp = new BicycleFacilitiesGovAreaGridVo();
            BeanUtil.copyProperties(bicycleFacilitiesGovArea, bicycleFacilitiesGovAreaResp);
            DataCacheOprator.getInstance().setRedisStringHelper(redisStringHelper);
            if (bicycleFacilitiesGovArea.getDistrict() != null) {
                bicycleFacilitiesGovAreaResp
                        .setDistrictName(DataCacheOprator.getInstance().getRegion(bicycleFacilitiesGovArea.getDistrict()).getRegionName());
            }
            if (bicycleFacilitiesGovArea.getStreet() != null) {
                bicycleFacilitiesGovAreaResp
                        .setStreetName(DataCacheOprator.getInstance().getRegion(bicycleFacilitiesGovArea.getStreet()).getRegionName());
            }
            bicycleFacilitiesGovAreaResps.add(bicycleFacilitiesGovAreaResp);
        });
        dataGrid.setTotal(page.getTotal());
        dataGrid.setRows(bicycleFacilitiesGovAreaResps);
        return dataGrid;
    }

    /**
     * 根据主键修改政府区域信息
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("根据主键修改区域信息")
    @RequestMapping(value = "/updateGovArea", method = {RequestMethod.POST})
    public Message updateGovArea(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea, HttpServletRequest httpServletRequest) {
        Message message = new Message();
        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        bicycleFacilitiesGovArea.setUpdateBy(userLoginResp.getSysUserId());
        bicycleFacilitiesGovArea.setUpdateName(userLoginResp.getUserName());
        message = facilitiesGovAreaService.updateFacilitiesGovAreaByPrimaryKey(bicycleFacilitiesGovArea);
        return message;
    }

    /**
     * 根据主键删除政府区域信息
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("根据主键删除区域信息")
    @RequestMapping(value = "/deleteGovArea", method = {RequestMethod.POST})
    public Message deleteGovArea(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea) {
        Message message = new Message();
        message = facilitiesGovAreaService.deleteFacilitiesGovAreaByPrimaryKey(bicycleFacilitiesGovArea.getId());
        return message;
    }

    /**
     * 新增政府区域信息
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("新增区域信息")
    @RequestMapping(value = "/insertGovArea", method = {RequestMethod.POST})
    public Message insertGovArea(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea, HttpServletRequest httpServletRequest) {
        Message message = new Message();
        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        bicycleFacilitiesGovArea.setCreateBy(userLoginResp.getSysUserId());
        bicycleFacilitiesGovArea.setCreateName(userLoginResp.getUserName());
        message = facilitiesGovAreaService.insertFacilitiesGovAreaSelective(bicycleFacilitiesGovArea);
        return message;
    }

    /**
     * 分页查询政府监控区区域列表信息
     *
     * @param bicycleFacilitiesGovAreaGridDto
     * @return
     * @see
     */
    @ApiOperation("分页查询监控区域列表信息")
    @RequestMapping(value = "/selectGovMonitorAreaGrid", method = {RequestMethod.POST})
    public DataGrid<BicycleFacilitiesGovAreaGridVo> selectGovMonitorAreaGrid(@RequestBody BicycleFacilitiesGovAreaGridDto bicycleFacilitiesGovAreaGridDto, HttpServletRequest httpServletRequest) {
        DataGrid dataGrid = new DataGrid();
        QueryWrapper<BicycleFacilitiesGovArea> queryWrapper = new QueryWrapper<BicycleFacilitiesGovArea>();
        BicycleFacilitiesGovArea queryEntity = new BicycleFacilitiesGovArea();

        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        if (userLoginResp.getRegionId() != null) {
            bicycleFacilitiesGovAreaGridDto.setDistrict(userLoginResp.getRegionId());
        }
        BeanUtil.copyProperties(bicycleFacilitiesGovAreaGridDto, queryEntity);
        queryEntity.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());

        if (StringUtils.isNotBlank(bicycleFacilitiesGovAreaGridDto.getAreaName())) {
            queryEntity.setAreaName(null);
            queryWrapper.like("area_name", bicycleFacilitiesGovAreaGridDto.getAreaName().trim());
        }
        if (StringUtils.isNotBlank(bicycleFacilitiesGovAreaGridDto.getAreaNo())) {
            queryEntity.setAreaNo(null);
            queryWrapper.like("area_no", bicycleFacilitiesGovAreaGridDto.getAreaNo());
        }
        // 创建时间区间段筛选
        if (bicycleFacilitiesGovAreaGridDto.getBeginTime() != null && bicycleFacilitiesGovAreaGridDto.getEndTime() != null) {
            queryWrapper.between("create_time", bicycleFacilitiesGovAreaGridDto.getBeginTime(), bicycleFacilitiesGovAreaGridDto.getEndTime());
        }
        queryWrapper.setEntity(queryEntity);
        queryWrapper.orderByDesc("create_time");

        IPage<BicycleFacilitiesGovArea> page = facilitiesGovAreaService.page(new Page<BicycleFacilitiesGovArea>(bicycleFacilitiesGovAreaGridDto.getPage(), bicycleFacilitiesGovAreaGridDto.getRows()), queryWrapper);

        List<BicycleFacilitiesGovAreaGridVo> bicycleFacilitiesGovAreaResps = new ArrayList<>();
        page.getRecords().forEach(bicycleFacilitiesGovArea -> {
            BicycleFacilitiesGovAreaGridVo bicycleFacilitiesGovAreaResp = new BicycleFacilitiesGovAreaGridVo();
            BeanUtil.copyProperties(bicycleFacilitiesGovArea, bicycleFacilitiesGovAreaResp);
            DataCacheOprator.getInstance().setRedisStringHelper(redisStringHelper);
            if (bicycleFacilitiesGovArea.getDistrict() != null) {
                bicycleFacilitiesGovAreaResp
                        .setDistrictName(DataCacheOprator.getInstance().getRegion(bicycleFacilitiesGovArea.getDistrict()).getRegionName());
            }
            if (bicycleFacilitiesGovArea.getStreet() != null) {
                bicycleFacilitiesGovAreaResp
                        .setStreetName(DataCacheOprator.getInstance().getRegion(bicycleFacilitiesGovArea.getStreet()).getRegionName());
            }
            bicycleFacilitiesGovAreaResps.add(bicycleFacilitiesGovAreaResp);
        });
        dataGrid.setTotal(page.getTotal());
        dataGrid.setRows(bicycleFacilitiesGovAreaResps);
        return dataGrid;
    }

    /**
     * 根据主键修改政府监控区区域信息
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("根据主键修改监控区区域信息")
    @RequestMapping(value = "/updateGovMonitorArea", method = {RequestMethod.POST})
    public Message updateGovMonitorArea(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea, HttpServletRequest httpServletRequest) {
        Message message = new Message();
        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        bicycleFacilitiesGovArea.setUpdateBy(userLoginResp.getSysUserId());
        bicycleFacilitiesGovArea.setUpdateName(userLoginResp.getUserName());
        message = facilitiesGovAreaService.updateFacilitiesGovAreaByPrimaryKey(bicycleFacilitiesGovArea);
        return message;
    }

    /**
     * 根据主键删除政府监控区区域信息
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("根据主键删除监控区区域信息")
    @RequestMapping(value = "/deleteGovMonitorArea", method = {RequestMethod.POST})
    public Message deleteGovMonitorArea(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea) {
        Message message = new Message();
        message = facilitiesGovAreaService.deleteFacilitiesGovAreaByPrimaryKey(bicycleFacilitiesGovArea.getId());
        return message;
    }

    /**
     * 新增政府监控区区域信息
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("新增监控区区域信息")
    @RequestMapping(value = "/insertGovMonitorArea", method = {RequestMethod.POST})
    public Message insertGovMonitorArea(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea, HttpServletRequest httpServletRequest) {
        Message message = new Message();
        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        bicycleFacilitiesGovArea.setCreateBy(userLoginResp.getSysUserId());
        bicycleFacilitiesGovArea.setCreateName(userLoginResp.getUserName());
        message = facilitiesGovAreaService.insertFacilitiesGovAreaSelective(bicycleFacilitiesGovArea);
        return message;
    }

    /**
     * 获取政府区域列表
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("获取区域列表")
    @RequestMapping(value = "/selectGovArea", method = {RequestMethod.POST})
    public Message<List<BicycleFacilitiesGovArea>> selectGovArea(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea) {
        Message message = new Message();
        bicycleFacilitiesGovArea.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());
        message.setResult(facilitiesGovAreaService.list(new QueryWrapper<BicycleFacilitiesGovArea>(bicycleFacilitiesGovArea)));
        return message;
    }

    /**
     * 根据主键ID获取政府详情信息
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
    @ApiOperation("根据主键ID获取详情信息")
    @RequestMapping(value = "/selectGovAreaDetail", method = {RequestMethod.POST})
    public Object selectGovAreaDetail(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea) {
        Message message = new Message();
        message.setResult(facilitiesGovAreaService.getById(bicycleFacilitiesGovArea.getId()));
        return message;
    }

    /**
     * 根据行政区街道获取政府区域数量
     *
     * @param bicycleFacilitiesGovArea
     * @return
     * @see
     */
//    @RequestMapping(value = "/selectGovAreaCount", method = { RequestMethod.POST})
//
//    public Object selectGovAreaCount(@RequestBody BicycleFacilitiesGovArea bicycleFacilitiesGovArea) {
//        Message message = new Message();
//        try {
//            bicycleFacilitiesGovArea.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());
//            message = facilitiesGovAreaService.selectBicycleFacilitiesGovAreaCount(bicycleFacilitiesGovArea);
//        } catch (ServiceException e) {
//            log.error("selectGovAreaCount error:", e);
//            message.setCode(e.getErrorCode());
//            message.setMessage(e.getErrorMsg());
//        }
//        return message;
//    }

    /**
     * 停放一张图
     *
     * @return
     */
    @ApiOperation("获取停放一张图位置信息")
    @RequestMapping(value = "/selectGovAreaMap", method = RequestMethod.POST)
    public Message selectGovAreaMap() {
        Message message = new Message();

        /*QueryWrapper<BicycleBasicsBicycle> queryBicycleWrapper = new QueryWrapper<BicycleBasicsBicycle>();
        if(environment.getProperty("region.district") != null) {
            queryBicycleWrapper.eq("district", environment.getProperty("region.district"));
        }
        if(environment.getProperty("region.street") != null) {
            queryBicycleWrapper.eq("street", environment.getProperty("region.street"));
        }
        queryBicycleWrapper.eq("lock_status",1);
        List<BicycleBasicsBicycle> bicycleSites = basicsBicycleService.list(queryBicycleWrapper);*/

        List<BicycleFacilitiesMapVo> bicycleFacilitiesMapVoList = new ArrayList<>();
        List<BicycleFacilitiesGovArea> govAreaList = facilitiesGovAreaService.list(new QueryWrapper<BicycleFacilitiesGovArea>(BicycleFacilitiesGovArea.builder().hasDel(HasDelEnum.HAS_DEL_FALSE.getKey()).areaStatus(AreaStatusEnum.AREA_STATUS_0.getKey()).build()));
        govAreaList.forEach(govArea -> {
            BicycleFacilitiesMapVo bicycleFacilitiesMapVo = new BicycleFacilitiesMapVo();
            if (govArea.getAreaAttribute() == GovAreaAttributeEnum.AREA_ATTRI_PARK.getKey().intValue()) {
                bicycleFacilitiesMapVo.setAreaPoints(govArea.getAreaPoints());
                bicycleFacilitiesMapVo.setLat(govArea.getLat());
                bicycleFacilitiesMapVo.setLng(govArea.getLng());
                bicycleFacilitiesMapVo.setType(0);
                bicycleFacilitiesMapVo.setAreaAddress(govArea.getAreaAddress());
                bicycleFacilitiesMapVo.setParkValue(govArea.getParkValue());
                /*QueryWrapper<BicycleBasicsAreaVehicle> queryVehicleWrapper = new QueryWrapper<BicycleBasicsAreaVehicle>();
                queryVehicleWrapper.eq("area_id",govArea.getId());
                List<BicycleBasicsAreaVehicle>  list = vehicleService.list(queryVehicleWrapper);
                if(list != null && list.size() > 0) {
                    bicycleFacilitiesMapVo.setParkNum(list.size());
                } else {
                    bicycleFacilitiesMapVo.setParkNum(0);
                }*/
                List<BicycleBasicsAreaVehicleDto> vehicleDto = vehicleService.selectAreaVehicleByAreaId(govArea.getId());
                if(vehicleDto != null && vehicleDto.size() > 0) {
                    bicycleFacilitiesMapVo.setVehicleDtoList(vehicleDto);
                    bicycleFacilitiesMapVo.setParkNum(vehicleDto.get(0).getTotalCount());
                }
                /*int parkNum = 0;
                if(bicycleSites != null && bicycleSites.size() > 0) {
                    for(BicycleBasicsBicycle basicsBicycle : bicycleSites) {
                        if(basicsBicycle != null) {
                            Point2D.Double point = new Point2D.Double(Double.parseDouble(basicsBicycle.getLat()), Double.parseDouble(basicsBicycle.getLng()));
                            List<JSONObject> objectList = JSON.parseObject(govArea.getAreaPoints(), ArrayList.class);
                            List<Point2D.Double> pts = new ArrayList<Point2D.Double>();
                            boolean distanceTrue = true;
                            for (JSONObject object : objectList) {
                                Point2D.Double p = new Point2D.Double(object.getDoubleValue("lat"), object.getDoubleValue("lng"));
                                pts.add(p);
                                if(distanceTrue) {//停放区，在原先停放区基础上，以车辆位置信息距离车框最近点有没有超过5米，超过则违停
                                    double distance = CoordinateHelper.getDistance(new Double(basicsBicycle.getLat()),
                                            new Double(basicsBicycle.getLng())
                                            ,object.getDoubleValue("lat"),object.getDoubleValue("lng"));
                                    if (distance <= Double.parseDouble(environment.getProperty("region.distance"))) {//两点距离小于等于5米，则不算违停
                                        distanceTrue = false;
                                    }
                                }
                            }
                            boolean hasArea = CoordinateHelper.IsPtInPoly(point, pts);
                            if (hasArea || !distanceTrue) {//在停放区或者距离停放区最近点距离小于等于5米
                                parkNum++;
//                                insertAreaVehicle(govArea,basicsBicycle);
                            }
                        }
                    }
                }
                bicycleFacilitiesMapVo.setParkNum(parkNum);*/
                bicycleFacilitiesMapVo.setArea(govArea.getArea());
                bicycleFacilitiesMapVoList.add(bicycleFacilitiesMapVo);
            }
        });
        message.setResult(bicycleFacilitiesMapVoList);
        return message;
    }

    private void insertAreaVehicle(BicycleFacilitiesGovArea govArea, BicycleBasicsBicycle basicsBicycle) {
        BicycleBasicsAreaVehicle areaVehicle = new BicycleBasicsAreaVehicle();
        areaVehicle.setEnterpriseNo(basicsBicycle.getEnterpriseNo());
        areaVehicle.setEnterpriseName(basicsBicycle.getEnterpriseName());
        areaVehicle.setVehicleNo(basicsBicycle.getVehicleNo());
        areaVehicle.setAreaId(govArea.getId());
        areaVehicle.setAreaAttribute(govArea.getAreaAttribute());
        QueryWrapper<BicycleBasicsAreaVehicle> queryWrapper = new QueryWrapper<BicycleBasicsAreaVehicle>();
        queryWrapper.eq("vehicle_no",basicsBicycle.getVehicleNo());
        queryWrapper.eq("area_attribute",1);
        BicycleBasicsAreaVehicle bicycleBasicsAreaVehicle = areaVehicleService.getOne(queryWrapper);
        if(bicycleBasicsAreaVehicle != null) {
            areaVehicleService.remove(queryWrapper);
        }
        areaVehicleService.save(areaVehicle);
    }

    /**
     * 停放一张图-图表数据
     *
     * @param
     * @return
     * @see
     */
//    @RequestMapping(value = "/selectGovAreaMapChart", method = {RequestMethod.GET, RequestMethod.POST})
//    @ResponseBody
//    public Object selectGovAreaMapChart() {
//        Message message = new Message();
//        try {
//            message = facilitiesGovAreaService.selectGovAreaMapChart();
//        } catch (ServiceException e) {
//            log.error("selectGovAreaMapChart error:", e);
//            message.setCode(e.getErrorCode());
//            message.setMessage(e.getErrorMsg());
//        }
//        return message;
//    }

    /**
     * 修改总量控制数量
     *
     * @param bicycleFacilitiesBicycleParkDto
     * @return
     * @see
     */
    @ApiOperation("修改总量控制数量")
    @RequestMapping(value = "/updateBicyclePark", method = {RequestMethod.POST})
    public Message updateBicyclePark(@RequestBody BicycleFacilitiesBicycleParkDto bicycleFacilitiesBicycleParkDto) {
        Message message = new Message();
        redisStringHelper.set("bicycle_park_count", String.valueOf(bicycleFacilitiesBicycleParkDto.getBicyclePark()));
        return message;
    }

    @ApiOperation("获取总量控制数量")
    @RequestMapping(value = "/selectBicyclePark", method = {RequestMethod.POST})
    public Message selectBicyclePark() {
        Message message = new Message();
        if (redisStringHelper.exists("bicycle_park_count")) {
            String bicycleParkCount = redisStringHelper.get("bicycle_park_count");
            message.setResult(Integer.valueOf(bicycleParkCount));
        } else {
            message.setResult(0);
        }

        return message;
    }

    @ApiOperation("批量导入停放区车辆位置信息")
    @RequestMapping(value = "/importAreaData", method = RequestMethod.POST)
    public Message importAreaData(@RequestParam(value="uploadFile",required=false) MultipartFile uploadFile, HttpServletRequest httpServletRequest) {
        Message message = new Message();
        String filePath = environment.getProperty("file.upload.path");
        try {
            BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
            String fileType = FilenameUtils.getExtension(uploadFile.getOriginalFilename());
            String fileName = UUID.randomUUID().toString() + "." + fileType;
            String prefix = "/profile/" + userLoginResp.getSysUserId() + "/" + fileType + DateUtils.MILLIS_PER_MINUTE;
            File copyFile = new File(filePath + prefix + fileName);
            if (!copyFile.getParentFile().exists()) {
                copyFile.getParentFile().mkdirs();
            }
            uploadFile.transferTo(copyFile);
            message = facilitiesGovAreaService.importFacilitiesGovAreaFile(copyFile,userLoginResp);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("importAreaData error:", e.getMessage());
            message.setCode(500);
            message.setMessage(e.getMessage());
        }
        return message;
    }

    @ApiOperation("查询未在市局备案、但出现在东门区域的车辆")
    @RequestMapping(value = "/getIllegalDeliveryList", method = {RequestMethod.POST})
    public Message getIllegalBicycleList() {
        Message message = new Message();
        JSONObject result = new JSONObject();
        QueryWrapper<BicycleBasicsBicycle> queryWrapper = new QueryWrapper<BicycleBasicsBicycle>();

        //按企业分组查询各企业未备案车辆数
        Map<String, Object> paramMap = new HashMap<>();
        if(environment.getProperty("region.district") != null) {
            paramMap.put("district", environment.getProperty("region.district"));
        }
        if(environment.getProperty("region.street") != null) {
            paramMap.put("street", environment.getProperty("region.street"));
        }
        List<BicycleBasicsBicycleMapDto> bicycleCount = basicsBicycleService.selectBicyclePutOnCount(paramMap);
        result.put("bicycleCount",bicycleCount);

        // 查询所有未备案车辆信息
        queryWrapper.eq("put_on_status", 0);
        if(environment.getProperty("region.district") != null) {
            queryWrapper.eq("district", environment.getProperty("region.district"));
        }
        if(environment.getProperty("region.street") != null) {
            queryWrapper.eq("street", environment.getProperty("region.street"));
        }
        List<BicycleBasicsBicycle> bicycleList = basicsBicycleService.list(queryWrapper);
        result.put("bicycleList",bicycleList);

        message.setResult(result);
        return message;
    }

    @ApiOperation("根据主键ID获取车框停车信息详情信息")
    @RequestMapping(value = "/getGovAreaBikeParkCount", method = {RequestMethod.POST})
    public Message getGovAreaBikeParkCount(@RequestBody BicycleFacilitiesGovAreaGridDto facilitiesGovAreaGridDto) {
        Message message = new Message();
        BicycleFacilitiesGovArea facilitiesGovArea = new BicycleFacilitiesGovArea();
        BicycleFacilitiesMapVo facilitiesMapVo = new BicycleFacilitiesMapVo();
        if(facilitiesGovAreaGridDto != null && facilitiesGovAreaGridDto.getDataType() == 0) {
            facilitiesGovArea = facilitiesGovAreaService.getById(facilitiesGovAreaGridDto.getId());
            facilitiesMapVo.setAreaPoints(facilitiesGovArea.getAreaPoints());
            if(StringUtils.isNoneBlank(facilitiesGovArea.getAreaName())) {
                facilitiesMapVo.setAreaName(facilitiesGovArea.getAreaName());
            } else {
                facilitiesMapVo.setAreaName(facilitiesGovArea.getAreaNo());
            }
            facilitiesMapVo.setAreaNo(facilitiesGovArea.getAreaNo());
            facilitiesMapVo.setParkValue(facilitiesGovArea.getParkValue());
            facilitiesMapVo.setArea(facilitiesGovArea.getArea());
            facilitiesMapVo.setAreaAddress(facilitiesGovArea.getAreaAddress());

            //获取停车框车辆数量
            List<BicycleBasicsAreaVehicleDto> vehicleDto = vehicleService.selectAreaVehicleByAreaId(facilitiesGovAreaGridDto.getId());
            if(vehicleDto != null && vehicleDto.size() > 0) {
                facilitiesMapVo.setVehicleDtoList(vehicleDto);
            }
            message.setResult(facilitiesMapVo);
        } else {
            List<BicycleBasicsAreaVehicleDto> basicsAreaVehicleDtos = new ArrayList<BicycleBasicsAreaVehicleDto>();
            DataCacheOprator.getInstance().setRedisStringHelper(redisStringHelper);
            List<BicycleCommonEnterprise> enterpriseList = DataCacheOprator.getInstance().getEnterpriseList();
            enterpriseList.forEach(enterprise -> {
                BicycleStatisGlobalVo.BicycleStatisGlobalEnterpriseVo enterpriseVo = new BicycleStatisGlobalVo.BicycleStatisGlobalEnterpriseVo();
                Integer bicycleCount = 0;
                BicycleBasicsAreaVehicleDto vehicleDto = new BicycleBasicsAreaVehicleDto();
                QueryWrapper<BicycleBasicsBicycle> queryWrapper = new QueryWrapper<BicycleBasicsBicycle>();
                if(environment.getProperty("region.district") != null) {
                    queryWrapper.eq("district", environment.getProperty("region.district"));
                }
                if(environment.getProperty("region.street") != null) {
                    queryWrapper.eq("street", environment.getProperty("region.street"));
                }
                queryWrapper.eq("has_illegal_park", 1);
//                queryWrapper.eq("lock_status", 1);
                queryWrapper.eq("enterprise_no", enterprise.getEnterpriseNo());
                bicycleCount = basicsBicycleService.count(queryWrapper);
                vehicleDto.setEnterpriseNo(enterprise.getEnterpriseNo());
                vehicleDto.setEnterpriseName(enterprise.getEnterpriseAlias());
                vehicleDto.setTotalCount(bicycleCount);
                basicsAreaVehicleDtos.add(vehicleDto);
            });
            Integer totalCount = 0;
            for(BicycleBasicsAreaVehicleDto vehicleDto : basicsAreaVehicleDtos) {
                totalCount = totalCount + vehicleDto.getTotalCount();
            }
            BicycleBasicsAreaVehicleDto vehicleDto = new BicycleBasicsAreaVehicleDto();
            vehicleDto.setEnterpriseNo("");
            vehicleDto.setEnterpriseName("未入框（违停）车辆数");
            vehicleDto.setTotalCount(totalCount);
            basicsAreaVehicleDtos.add(0,vehicleDto);
            message.setResult(basicsAreaVehicleDtos);
        }
        return message;
    }

    @ApiOperation("查询实时车辆位置信息")
    @RequestMapping(value = "/getRealTimeBicycleList", method = {RequestMethod.POST})
    public Message getRealTimeBicycleList() {
        Message message = new Message();

        QueryWrapper<BicycleBasicsBicycle> queryWrapper = new QueryWrapper<BicycleBasicsBicycle>();
        if(environment.getProperty("region.district") != null) {
            queryWrapper.eq("district", environment.getProperty("region.district"));
        }
        if(environment.getProperty("region.street") != null) {
            queryWrapper.eq("street", environment.getProperty("region.street"));
        }
        queryWrapper.eq("put_on_status",1);
        queryWrapper.eq("lock_status",1);
        List<BicycleBasicsBicycle> bicycleSites = basicsBicycleService.list(queryWrapper);

        message.setResult(bicycleSites);
        return message;
    }


    /**
     * @Description: 停放区位置信息表导出
     * @Author: zhouzm
     * @Date: 2021/7/17 12:37
     * @param request:
     * @param response:
     * @return: java.lang.Object
     **/
    @RequestMapping(value = "/downloadGovAreaData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void downloadGovAreaData(HttpServletRequest request, HttpServletResponse response) {
        //获取数据
        List<BicycleFacilitiesGovArea> govAreaList = facilitiesGovAreaService.list(new QueryWrapper<BicycleFacilitiesGovArea>(BicycleFacilitiesGovArea.builder().hasDel(HasDelEnum.HAS_DEL_FALSE.getKey()).areaStatus(AreaStatusEnum.AREA_STATUS_0.getKey()).areaAttribute(0).build()));

        //excel标题
        String[] title = {"停放区名称","停放区编号","纬度","经度","行政区","街道","停放容量","区域状态","是否删除","区域类型","区域属性","有效期开始时间","有效期结束时间","区域位置","区域坐标点"};

        //excel文件名
        String fileName = "停放区信息表" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "停放区信息表";

        String [][] content = new String[govAreaList.size()][15];

        for (int i = 0; i < govAreaList.size(); i++) {
            content[i] = new String[title.length];
            BicycleFacilitiesGovArea obj = govAreaList.get(i);
            content[i][0] = obj.getAreaName();
            content[i][1] = obj.getAreaNo();
            content[i][2] = obj.getLat();
            content[i][3] = obj.getLng();
            content[i][4] = obj.getDistrict() + "";
            content[i][5] = obj.getStreet() + "";
            content[i][6] = obj.getArea() + "";
            if(obj.getAreaStatus() == 0) {//区域状态：0：正常，1：规划中，2：停用，3：废除
                content[i][7] = "正常";
            } else  if(obj.getAreaStatus() == 1) {
                content[i][7] = "规划中";
            } else  if(obj.getAreaStatus() == 2) {
                content[i][7] = "停用";
            } else {
                content[i][7] = "废除";
            }
            if(obj.getHasDel() == 0) {//是否删除 0：未删除 1：:已删除
                content[i][8] = obj.getHasDel() + "未删除";
            } else {
                content[i][8] = obj.getHasDel() + "已删除";
            }
            if(obj.getAreaType() == 0) {//区域类型：0：停放区，1：禁停区，2：规范停放区，3：动态调节区，4：临时管控区
                content[i][9] = "停放区";
            } else if(obj.getAreaType() == 1) {
                content[i][9] = "禁停区";
            } else if(obj.getAreaType() == 2) {
                content[i][9] = "规范停放区";
            } else if(obj.getAreaType() == 3) {
                content[i][9] = "动态调节区";
            } else {
                content[i][9] = "临时管控区";
            }
            if(obj.getAreaAttribute() == 0) { //区域属性：0：停放区，1：监控区，2：禁停区
                content[i][10] = "停放区";
            } else if(obj.getAreaAttribute() == 1) {
                content[i][10] = "监控区";
            } else {
                content[i][10] = "禁停区";
            }
            content[i][11] = obj.getPeriodBegin() + "";
            content[i][12] = obj.getPeriodEnd() + "";
            content[i][13] = obj.getAreaAddress();
            content[i][14] = obj.getAreaPoints();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelHelper.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            ExcelHelper.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 违投车辆信息导出
     * @Author: zhouzm
     * @Date: 2021/7/17 12:37
     * @param bicycleBasicsBicycleVo:
     * @param response:
     * @return: java.lang.Object
     **/
    @RequestMapping(value = "/downloadIllegalDeliveryData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void downloadIllegalDeliveryData(@RequestBody BicycleBasicsBicycleVo bicycleBasicsBicycleVo, HttpServletResponse response) {
        //获取数据
        QueryWrapper<BicycleBasicsBicycle> queryWrapper = new QueryWrapper<BicycleBasicsBicycle>();
        queryWrapper.eq("put_on_status", 0);
        if(environment.getProperty("region.district") != null) {
            queryWrapper.eq("district", environment.getProperty("region.district"));
        }
        if(environment.getProperty("region.street") != null) {
            queryWrapper.eq("street", environment.getProperty("region.street"));
        }

        if (StringUtils.isNotBlank(bicycleBasicsBicycleVo.getEnterpriseNo())) {
            queryWrapper.like("enterprise_no", bicycleBasicsBicycleVo.getEnterpriseNo());
        }
        if (bicycleBasicsBicycleVo.getBeginTime() != null && bicycleBasicsBicycleVo.getEndTime() != null) {
            queryWrapper.between("gnss_time", bicycleBasicsBicycleVo.getBeginTime(), bicycleBasicsBicycleVo.getEndTime());
        }

        queryWrapper.groupBy("vehicle_no");
        List<BicycleBasicsBicycle> bicycleList = basicsBicycleService.list(queryWrapper);

        //excel标题
        String[] title = {"企业编号","企业名称","车辆编号","行政区","街道","定位时间","纬度","经度","车锁状态"};

        //excel文件名
        String fileName = "违投车辆信息表" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "违投车辆信息表";

        String [][] content = new String[bicycleList.size()][9];

        for (int i = 0; i < bicycleList.size(); i++) {
            content[i] = new String[title.length];
            BicycleBasicsBicycle obj = bicycleList.get(i);
            content[i][0] = obj.getEnterpriseNo();
            content[i][1] = obj.getEnterpriseName();
            content[i][2] = obj.getVehicleNo();
            content[i][3] = obj.getDistrict() + "";
            content[i][4] = obj.getStreet() + "";
            content[i][5] = obj.getGnssTime() + "";
            content[i][6] = obj.getLat();
            content[i][7] = obj.getLng();
            if(obj.getLockStatus() == 0) {
                content[i][8] = "开";
            } else {
                content[i][8] ="关";
            }
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelHelper.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            ExcelHelper.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 停放一张图车辆信息导出
     * @Author: zhouzm
     * @Date: 2021/7/17 12:37
     * @param bicycleBasicsBicycleVo:
     * @param response:
     * @return: java.lang.Object
     **/
    @RequestMapping(value = "/downloadParkMapData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void downloadParkMapData(@RequestBody BicycleBasicsBicycleVo bicycleBasicsBicycleVo, HttpServletResponse response) {
        //获取数据
        QueryWrapper<BicycleBasicsBicycle> queryWrapper = new QueryWrapper<BicycleBasicsBicycle>();
        if(environment.getProperty("region.district") != null) {
            queryWrapper.eq("district", environment.getProperty("region.district"));
        }
        if(environment.getProperty("region.street") != null) {
            queryWrapper.eq("street", environment.getProperty("region.street"));
        }
        queryWrapper.eq("put_on_status",1);
        queryWrapper.eq("lock_status",1);

        if (StringUtils.isNotBlank(bicycleBasicsBicycleVo.getEnterpriseNo())) {
            queryWrapper.like("enterprise_no", bicycleBasicsBicycleVo.getEnterpriseNo());
        }
        if (bicycleBasicsBicycleVo.getBeginTime() != null && bicycleBasicsBicycleVo.getEndTime() != null) {
            queryWrapper.between("gnss_time", bicycleBasicsBicycleVo.getBeginTime(), bicycleBasicsBicycleVo.getEndTime());
        }

        queryWrapper.groupBy("vehicle_no");
        List<BicycleBasicsBicycle> bicycleList = basicsBicycleService.list(queryWrapper);

        //企业信息
        DataCacheOprator.getInstance().setRedisStringHelper(redisStringHelper);

        //excel标题
        String[] title = {"企业编号","企业名称","车辆编号","行政区","街道","定位时间","纬度","经度","车锁状态"};

        //excel文件名
        String fileName = "停放一张图车辆信息表" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "停放一张图车辆信息表";

        String [][] content = new String[bicycleList.size()][9];

        for (int i = 0; i < bicycleList.size(); i++) {
            content[i] = new String[title.length];
            BicycleBasicsBicycle obj = bicycleList.get(i);
            content[i][0] = obj.getEnterpriseNo();
            content[i][1] = obj.getEnterpriseName();
            content[i][2] = obj.getVehicleNo();
            content[i][3] = obj.getDistrict() + "";
            content[i][4] = obj.getStreet() + "";
            content[i][5] = obj.getGnssTime() + "";
            content[i][6] = obj.getLat() + "";
            content[i][7] = obj.getLng() + "";
            if(obj.getLockStatus() == 0) {
                content[i][8] = "开";
            } else {
                content[i][8] ="关";
            }
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelHelper.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            ExcelHelper.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
